﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace QldtSdh.Utils
{
    class XMLTreeView
    {
        public static void PopulateTreeview(string xml, TreeNode rootNode)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xml);
                addTreeNode(xDoc.DocumentElement, rootNode);
            }
            catch (XmlException ex)
            {
                throw new Exception("Lỗi định dạng file XML. Chi tiết: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi. Chi tiết: " + ex.Message);
            }
        }

        private static void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            if (xmlNode.HasChildNodes)
            {
                xNodeList = xmlNode.ChildNodes;
                for (int x = 0; x <= xNodeList.Count - 1; x++)
                {
                    xNode = xmlNode.ChildNodes[x];
                    treeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = treeNode.Nodes[x];
                    addTreeNode(xNode, tNode);
                }
            }
            else
                treeNode.Text = xmlNode.OuterXml.Trim();
        }
    }
}
